// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './store'
import 'font-awesome/css/font-awesome.min.css'
import './styles/lcd.scss';
// import md5 from 'js-md5'
import axios from 'axios';
import moment from 'moment'
moment.locale('zh-cn')
import { user, initUserInfo } from '@/utils/role.js'
import { printLog } from '@/utils/console.js'

Vue.use(Element, {
  size: 'medium'
})

Vue.config.productionTip = false

axios.defaults.withCredentials = true

// 拦截request,设置全局请求为ajax请求
axios.interceptors.request.use((config) => {
  // config.headers['_pid'] = '123'
  return config
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // printLog("::-:"+response.data.code);
  var code = response.data.code;
  if(code && code == -99000) {
    printLog("setSessionValid: false");
    if (user()) {
      sessionStorage.removeItem(user().id + '_sessionToken');
    }
    store.dispatch('setSessionValid', false);
  }
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

printLog('main.js')

router.beforeEach((to, from, next) => {
  printLog(to)
  // var cuid = to.query.cuid ? to.query.cuid : user().id
  var cuid = "test"
  if (cuid) {
    // initUserInfo(JSON.parse(window.sessionStorage.getItem(cuid + '_userInfo')))
  }
  
  if (to.path == '/login') {
    if (cuid) {
      sessionStorage.removeItem(cuid + '_sessionToken');
    }
  }
  let sessionToken = sessionStorage.getItem(cuid + '_sessionToken'); //JSON.parse(sessionStorage.getItem('sessionToken'));
  if (!sessionToken && to.path != '/login') {
    next({ path: '/login' })
  } else {
    if (user()) {
      sessionStorage.setItem(user().id + '_lastPath', to.path);
      sessionStorage.setItem(user().id + '_lastParams', JSON.stringify(to.params));
      sessionStorage.setItem(user().id + '_lastQuery', JSON.stringify(to.query));
    }
    next()
  }
})

// window.addEventListener('beforeunload', function() {
//   printLog('window.addEventListener beforeunload')
//   printLog(user())
// }, true)

// window.addEventListener('load', function(){
//   printLog　('window.addEventListener load')
//   printLog(user())
// }, true)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
